<template>
	<div class="definitions">
		<p v-if="!props.searchWord" class="tip">Start by typing a word in search ....</p>
		<p v-else-if="props.searchWord && !result.length">Sorry,the definition of this word was not found</p>
		<div v-else class="definition" v-for="(item, index) in result" :key="index">
			<!-- 音标 读音 -->
			<div class="phonetics">
				<span class="phonetic" @click="handleCLick(index)">
					{{ item?.phonetics[0]?.text || '暂无音标' }}
				</span>
				<i class="iconfont icon-shengyin" @click="handleCLick(index)"></i>
				<audio :src="item?.phonetics[0]?.audio" ref="audio"></audio>
			</div>
			<!-- 词性 -->
			<div class="meanings">
				<div class="meaning" v-for="(mean, index) in item.meanings" :key="index">
					<span class="partOfSpeech">{{ mean.partOfSpeech }}</span>
					<span class="partOfSpeech">{{ mean.definitions.map(item => item.definition).join(' ') }}</span>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import axios from 'axios';
import { watch, ref } from 'vue';

const props = defineProps(['searchWord']);
const audio = ref();

watch(
	() => props.searchWord,
	newVal => {
		getDate(newVal);
	}
);

const result = ref([]);

async function getDate(newVal) {
	const url = `https://api.dictionaryapi.dev/api/v2/entries/en/${newVal}`;
	result.value = [];
	try {
		let res = await axios.get(url);
		console.log(res.data);
		result.value = res.data;
	} catch (error) {
		console.log(error);
	}
}

function handleCLick(i) {
	audio.value[i].play();
}
</script>

<style scoped lang="less">
// 滚动条样式
::-webkit-scrollbar {
	width: 5px;
	background: #282c34;
}

::-webkit-scrollbar-thumb {
	background: rgba(255, 255, 255, 0.6);
	border-radius: 20px;
}

.definitions {
	border: 10px solid #696969;
	border-radius: 10px;
	height: 55vh;
	padding: 15px;
	overflow-y: scroll;
	display: flex;
	flex-direction: column;
	gap: 5px;

	.tip {
		font-size: 18px;
	}
	.definition {
		margin-bottom: 10px;
		.phonetics {
			margin-bottom: 10px;
			.phonetic {
				cursor: pointer;
				border-radius: 5px;

				margin-right: 10px;
				&:hover {
					opacity: 0.8;
				}
			}
			.iconfont {
				cursor: pointer;
				&:hover {
					opacity: 0.8;
				}
			}
		}
		&:last-child {
			.meanings {
				border-bottom: none;
			}
		}
		.meanings {
			display: flex;
			flex-direction: column;
			gap: 10px;
			padding-bottom: 10px;
			border-bottom: 1px solid #c5bcbc;

			div.meaning {
				.partOfSpeech {
					margin-right: 10px;
					background-color: #3b3e45;
					opacity: 0.8;
					display: inline-block;
					padding-block: 3px;
					padding-inline: 5px;
					font-size: 14px;
					border-radius: 5px;
					line-height: 25px;
				}
				.word-meaning {
					line-height: 25px;
				}
			}
		}
	}
}
</style>
